﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using CdmDeviceHealthMvc.Models;
using SnShared.Models;

namespace CdmDeviceHealthMvc.Controllers
{
    public class RemovePackagesController : ApiController
    {
        private CdmDataCtx db = CdmDataCtx.CreateDbContext();
        
        // POST: api/RemovePackages
        [ResponseType(typeof(RemovePackage))]
        public IHttpActionResult PostRemovePackage(RemovePackage removePackage)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
                      
                SoftwarePackage package = db.SoftwarePackages.Include("Computers").Where(o => o.UniqueId.Equals(removePackage.Package.UniqueId)).FirstOrDefault();
                 
                if (package != null)
                {               
                    Computer c = package.Computers.Where(o => o.Name.Equals(removePackage.ComputerName)).SingleOrDefault();                 
                    if (c != null)                        
                    {
                        package.Computers.Remove(c);                            
                        db.Entry(package).State = EntityState.Modified;
                        db.SaveChanges();
                    }                    
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e, "PostRemovePackage");
                throw;
            }
            
            return Ok(removePackage);
        }
        
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }   
    }
}